<?php
/**
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Esther Brunner <wikidesign@gmail.com>
 */

// must be run within Dokuwiki
if(!defined('DOKU_INC')) die();

if (!defined('DOKU_LF')) define('DOKU_LF', "\n");
if (!defined('DOKU_TAB')) define('DOKU_TAB', "\t");


if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
require_once(DOKU_PLUGIN.'action.php');

class action_plugin_object extends DokuWiki_Action_Plugin {

  /**
   * return some info
   */
  function getInfo(){
    return array(
      'author' => 'Martin Neitz',
      'email'  => 'mneitz@gmail.com',
      'date'   => '2007-01-22',
      'name'   => 'Object Plugin',
      'desc'   => 'Allows the creation of generic Objects via an entry screen',
      'url'    => '',
    );
  }

  /**
   * register the eventhandlers
   */
  function register(&$contr){
    $contr->register_hook('ACTION_ACT_PREPROCESS',
                          'BEFORE',
                          $this,
                          'handle_act_preprocess',
                           array());

    $contr->register_hook('IO_WIKIPAGE_WRITE',
                          'AFTER',
                          $this,
                          'io_wikipage_write',
                           array());                           
                           
                           
  }
    
  function io_wikipage_write($event){
  
  /**
   * update the meta data information of the object
   */     
   
//   $found = preg_match('*OBJECT*OBJECT*', $event->data[0][1] );

     if (substr($event->data[0][0],-3) !== "txt") return false;

     $startpos = strrchr($event->data[0][1], "<OBJECT>");
     if (!$startpos) return false; 
     $startpos = $startpos + 8;
     $endpos   = strrchr($event->data[0][1], "</OBJECT>");
     if (!$endpos) return false;

  }  
    
  /**
   * Checks if 'newentry' was given as action, if so we
   * do handle the event our self and no further checking takes place
   */
  function handle_act_preprocess(&$event, $param){
    if ($event->data != 'object_addobj' and $event->data != 'object_chgobj')
      return; // nothing to do for us
    // we can handle it -> prevent others
          
    $event->stopPropagation();
    $event->preventDefault();    
    
    switch ($event->data){
    case 'object_addobj':
      $event->data = $this->_addObject();
      break;
    case 'object_chgobj':
      $event->data = $this->_changeObject();
      break;
    }
  }

  /**
   * Creates a new object
   */
  function _addObject(){
    global $ID;
    global $INFO;
    
    
    include($_REQUEST['spcpath'] . '\\' . $_REQUEST['objspc'] . '\\objspc.php');
    
    $ns    = cleanID($_REQUEST['ns']);
    $title = str_replace(':', '', $_REQUEST[ $objid ]);
    $back  = $ID;
    $ID    = ($ns ? $ns.':' : '').cleanID($title);
    $INFO  = pageinfo();
    
    
    
    // check if we are allowed to create this file
    if ($INFO['perm'] >= AUTH_CREATE){
            
      //check if locked by anyone - if not lock for my self      
      if ($INFO['locked']) return 'locked';
      else lock($ID);

      // prepare the new thread file with default stuff
      if (!@file_exists($INFO['filepath'])){
        global $TEXT;
        
        $user     = $_REQUEST['user'];
        $username = $_SERVER['REMOTE_USER'];
        $fullname = $INFO['userinfo']['name'];

        
        // create wiki page
        $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title));
        if (!$TEXT){
        // get the default _template.txt from the task plugin folder
          $TEXT = io_readFile(DOKU_PLUGIN.'object/objspc/' . $_REQUEST['objspc'] . '/_template.txt');
          // the next statment only works with the change in the common.php (next release)
          $TEXT = replacePattern($TEXT);
        }
        
        $backlink   = "[[:$back]]";
        $tag        = "{{tag>}}";
        $discussion = "~~DISCUSSION~~";
        
        $TEXT = str_replace('@BACKLINK@'  ,$backlink    ,$TEXT);
        $TEXT = str_replace('@TITLE@'     ,$title       ,$TEXT);
        
        $TEXT = str_replace('@OBJECT@'    ,$this->_writeObjStr($_REQUEST['objspc'] ,$_REQUEST['spcpath']) ,$TEXT);
       
        if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php'))
          && (!plugin_isdisabled('tag'))){
          $TEXT = str_replace('@TAG@' ,$tag ,$TEXT);
          }else{
          $TEXT = str_replace('@TAG@' ,"" ,$TEXT);
        }
        if ((@file_exists(DOKU_PLUGIN.'discussion/action.php'))
          && (!plugin_isdisabled('discussion'))){
          $TEXT = str_replace('@DISCUSSION@',$discussion  ,$TEXT);
          }else{
          $TEXT = str_replace('@DISCUSSION@',""  ,$TEXT);
        }
       
        return 'preview';
      } else {
        return 'edit';
      }
    } else {
      return 'show';
    }
  }
  
  function _writeObjStr($objspc, $specificationPath){
      include($specificationPath . '\\' . $objspc . '\\objspc.php');
  
      $ret = '<OBJECT:'. $objspc .'>'. DOKU_LF;
       
      foreach($os as $fieldname => $element){
        switch ($element[0]){
          case 'seperator':
            break;
          case 'descriptivtext':
            break;            
          default: 
            if  (!empty($_REQUEST['obj_' . $fieldname])){ 
            $ret .= ' -' . $fieldname . '= ' . $_REQUEST['obj_' . $fieldname] . DOKU_LF;
            }
        }   
      }

      $ret .= '</OBJECT>'. DOKU_LF;
  
    return $ret;
  }
  
  /**
   * Change an existing object
   */
  function _changeObject(){
    global $ID;
    global $INFO;
    
    
    include($_REQUEST['spcpath'] . '\\' . $_REQUEST['objspc'] . '\\objspc.php');
    
    $ns    = cleanID($_REQUEST['ns']);
    $title = str_replace(':', '', $_REQUEST[ $objid ]);
    $back  = $ID;
    $ID    = ($ns ? $ns.':' : '').cleanID($title);
    $INFO  = pageinfo();
    
    
    
    // check if we are allowed to create this file
    if ($INFO['perm'] >= AUTH_CREATE){
            
      //check if locked by anyone - if not lock for my self      
      if ($INFO['locked']) return 'locked';
      else lock($ID);

      return 'show';
    }
  }  
  
  
  
}

//Setup VIM: ex: et ts=4 enc=utf-8 :
